
const int analogInPin = A0;  // 模拟采集端口引脚号

int sensorValue = 0;         // 模拟值存储变量
char count = 0;
char outputValue = 0;

char Tx_Buf[8] = { 0x5A,0xA5,0x05,0x01,0x02,0x03,0x04,0x05 };

void setup() 
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

unsigned char recv_count = 0;
unsigned char recv_success_flag = 0;
unsigned char recv_buf[10];

void loop() {
  
    sensorValue = analogRead(analogInPin);            /* 读取模拟端口 */
    outputValue = map(sensorValue, 0, 1023, 255, 0);  /* 数据映射 */
  
    count++;
    if(count>50) count = 0;
    
    Tx_Buf[3] = outputValue;
    Tx_Buf[4] = count;
    Serial.print(Tx_Buf);
    
  /*  数据接收成功,控制LED灯亮灭 */
  if(1==recv_success_flag)
  {
      recv_success_flag = 0;         
      //Serial.write('a');    
      if(0x01 == recv_buf[3]){ digitalWrite(13, HIGH); }
      if(0x00 == recv_buf[3]){ digitalWrite(13, LOW); } 
  }
  delay(50);
}

/******* 串口事件接收 ***********/
String inputString = "";  
bool stringComplete = false; 
void serialEvent() 
{
    /* 接收到字符缓存中 */
    while(Serial.available()>0)
    {
        char inChar = (char)Serial.read();
        inputString += inChar;    
        if (inChar == 0x0D) 
        {
          stringComplete = true;
          recv_count = 0;
        }
    }

    /* 解析接收到的数据是否符合要求 */
    if( stringComplete )
    {
        stringComplete = false;

        /* 起始位1、起始位2寻找判断 */
        char head1 = inputString.indexOf(0x5A);
        char head2 = inputString.indexOf(0xA5);
        //Serial.write(inputString[head2+1]);

        /********* 判断数据长度是否合适 **********/
        if( inputString[head2+1]>0 && inputString[head2+1]<10 )
        {
            /* 将数据转移到命令缓冲区中 */
            for(char i=head1; i<inputString.length(); i++ )
            {
                recv_buf[recv_count] = inputString[i];
                //Serial.write(recv_buf[recv_count]);   
                recv_count++;
                if(0x0D==inputString[i])
                {
                   recv_success_flag = 1;
                   recv_count = 0;
                }
            }    
        }
        inputString = "";   /* 清空字符接收缓冲区 */
    }
}